package me.android.library.utils.android;

import android.content.ContentValues;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import lombok.experimental.UtilityClass;

@UtilityClass
public class ContentValuesUtil {
    public <T> Collection<ContentValues> fromBeans(Collection<T> beans) {
        return beans.stream().map(ContentValuesUtil::fromBean).collect(Collectors.toSet());
    }

    public <T> ContentValues fromBean(T bean) {
        Map<String, Object> map = BeanUtil.beanToMap(bean);
        return fromMap(map);
    }

    public ContentValues fromMap(Map<String, Object> map) {
        ContentValues values = new ContentValues();
        map.forEach((key, value) -> {
            if (value == null) {
                values.putNull(key);
            } else if (value instanceof byte[]) {
                values.put(key, (byte[]) value);
            } else if (value instanceof Boolean) {
                values.put(key, (Boolean) value);
            } else if (value instanceof Byte) {
                values.put(key, (Byte) value);
            } else if (value instanceof Integer) {
                values.put(key, (Integer) value);
            } else if (value instanceof Long) {
                values.put(key, (Long) value);
            } else if (value instanceof Float) {
                values.put(key, (Float) value);
            } else if (value instanceof Double) {
                values.put(key, (Double) value);
            } else {
                values.put(key, value.toString());
            }
        });
        return values;
    }
}
